// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import {Toast} from 'vant'

// 引入vant-ui组件库
import Vant from 'vant'
// 注册组件库
Vue.use(Vant)
import 'vant/lib/index.css'

// axios库
import axios from "axios"
// 绑定原型
Vue.prototype.$axios = axios;
// 设置默认的api域名   基准路径
axios.defaults.baseURL ='http://111.230.181.206:3000'
// axios.defaults.baseURL ='http://127.0.0.1:3000'

Vue.config.productionTip = false

//  axios 响应拦截器
  axios.interceptors.response.use(res=>{
    const {message , statusCode} = res.data;
    if(message && statusCode ==401){
      Toast.fail(message)
    }
    // 响应拦截 token 错误,跳转到登录页
    if(message =='用户信息验证失败'){
      router.push('/login')
    }
    return(res)
  })

  // 路由守卫
  router.beforeEach((to,from,next)=>{
    var token =localStorage.getItem('token');
    const pagesNeedAuth =[
      '/profile',
      'editprofile'
    ]
    // 判断去个人中心的逻辑
    if(pagesNeedAuth.indexOf(to.path) >=0){
      // 如果有登陆过
      if(token){
        next()
      }else{
        // 没登陆过就去登录页
        next('/login')
      }
    }else{
      next()
    }
  })

  // 请求拦截器
  axios.interceptors.request.use(config=>{
    if(!config.headers.Authorization && localStorage.getItem('token')){
      config.headers.Authorization=localStorage.getItem('token')
    }
    return config
  })
  
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
